package feng.demo.service;

import feng.demo.dao.BreedDao;
import feng.demo.dao.TypeDao;
import feng.demo.entity.Breed;
import feng.demo.entity.Breeds;
import feng.demo.entity.Type;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
@CacheConfig(cacheNames = {"breed"})
public class BreedServiceImpl implements BreedService{
    @Autowired
    BreedDao breedDao;
    @Autowired
    TypeDao typeDao;
    @Override
    @Cacheable
    public List<Breed> findAll() {
        return breedDao.findAll();
    }

    @Override
    @Cacheable(key = "#p0")
    public Breed findById(Integer breedid) {
        return breedDao.findById(breedid);
    }

    @Override
    @CacheEvict(value = "breed", allEntries = true)
    public int add(Breed breed) {
        return breedDao.add(breed);
    }

    @Override
    @CacheEvict(value = "breed", allEntries = true)
    public int del(Integer breedid) {
        return breedDao.del(breedid);
    }

    @Override
    @CacheEvict(value = "breed", allEntries = true)
    public int update(Breed breed) {
        return breedDao.update(breed);
    }

    @Override
    @Cacheable
    public List<Breed> findBreed(Map<String, Object> map) {
        return breedDao.findBreed(map);
    }

    @Override
    @Cacheable
    public List<Breeds> findAlls() {
        List<Breeds> breeds = breedDao.findAlls();
        return doadds(breeds);
    }

    @Override
    @Cacheable
    public List<Breeds> findAllsLimit(Integer pagenum, Integer lines) {
        List<Breeds> breeds = breedDao.findAllsLimit(pagenum, lines);
        return doadds(breeds);
    }

    @Override
    public int findCount() {
        return breedDao.findCount();
    }

    private List<Breeds> doadds(List<Breeds> list){
        for (Breeds b:list) {
            List<Type> types = typeDao.findByBreedId(b.getBreedid());
            b.setTypes(types);
        }
        return list;
    }
}
